package com.cennavi.mineplay.mineplay_data.init;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.cennavi.mineplay.mineplay_data.model.DBTask;
import com.cennavi.mineplay.mineplay_data.model.DBTaskAssember;
import com.cennavi.mineplay.mineplay_data.model.HttpTask;
import com.cennavi.mineplay.mineplay_data.model.HttpTaskAssember;
import com.cennavi.mineplay.mineplay_data.model.TableCreateTask;

@Component
public class InitTask  implements ApplicationRunner{

	@Autowired
	protected JdbcTemplate jdbc;
	
	@Value("${spring.datasource.url}")
	private String destDBJdbc;
	
	@Value("${spring.datasource.username}")
	private String username;
	
	@Value("${spring.datasource.password}")
	private String password;
	
	@Value("${spring.datasource.driver-class-name}")
	private String dbDriverClass;
	
	@Value("${table.name}")
	private String destTableNames;
	
	public static final Map<String,String> transList = new HashMap<String,String>();
	
	@Override
	public void run(ApplicationArguments arg0) throws Exception {
		
		Thread createTable = new TableCreateTask(3, jdbc);
		
		createTable.start();
		
		
		
		transList.put("1", "com.cennavi.mineplay.mineplay_data.model.transform.inter.TransformImpl");

		System.out.println("-----init start------");
		
		String sql = "select param from task_param";
		
		List<Map<String,Object>> list = jdbc.queryForList(sql);
		
		for(Map<String,Object> m: list){
			String param = m.get("param").toString();
			
			JSONObject json = JSONObject.parseObject(param);
			
			String datasourcetype = json.getString("datasourcetype");
			
			if ("http".equals(datasourcetype)){
				HttpTask task = new HttpTaskAssember(json, 
						destDBJdbc,
						dbDriverClass,
						username, 
						password, 
						destTableNames).assember();
				
				task.start();
			}else if ("db".equals(datasourcetype)){
				DBTask task = new DBTaskAssember(json, 
						destDBJdbc,
						dbDriverClass,
						username, 
						password, 
						destTableNames).assember();
				
				task.start();
			}
		}
		
		System.out.println("-----init over-----");
	
	}

}
